package com.sh.example.consumer;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.sh.example.common.model.User;
import com.sh.example.common.service.UserService;
import com.sh.rpc.model.RpcRequest;
import com.sh.rpc.model.RpcResponse;
import com.sh.rpc.serializer.JdkSerializer;
import com.sh.rpc.serializer.Serializer;

/**
 * 静态代理
 */
public class UserServiceProxy implements UserService{

    public User getUser(User user) {
        Serializer serializer = new JdkSerializer();  // 序列化器

        // 构造请求对象
        RpcRequest rpcRequest = RpcRequest.builder()
                .serviceName(UserService.class.getName())
                .methodName("getUser")
                .parameterTypes(new Class[]{User.class})
                .args(new Object[]{user})
                .build();

        try {
            byte[] bodyBytes = serializer.serialize(rpcRequest);   // 序列化请求对象
            byte[] result;

            try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8082")   //  向RPC服务发请求
                    .body(bodyBytes)  //  设置请求体
                    .execute()  //  执行请求
            ) {
                result = httpResponse.bodyBytes();
            }

            // 反序列化响应对象，获取结果
            RpcResponse rpcResponse  = serializer.deserialize(result, RpcResponse.class );
            return (User) rpcResponse.getData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
